#ifndef __PRINTER_CONTROLLER__
#define __PRINTER_CONTROLLER__

#include <QObject>
#include <QThread>
#include <QSerialPort>
#include <QMutex>

#include "common.h"

class Coordinator;
class QTimer;
class QTextCodec;
class QImage;

class PrtController_Worker : public QObject
{
	Q_OBJECT

public:

	struct SerialConfig {
		QString port;
		uint32_t baud = QSerialPort::Baud115200;
		QSerialPort::DataBits data_bits = QSerialPort::Data8;
		QSerialPort::StopBits stop_bits = QSerialPort::OneStop;
		QSerialPort::Parity parity = QSerialPort::NoParity;
	};
	typedef struct SerialConfig SerialConfig;

    PrtController_Worker(QObject *parent = nullptr);
    ~PrtController_Worker();

    void setSerialParam(SerialConfig param);
    void setLogoImage(QImage *logo) { m_logo = logo; };

    bool online() { return m_online; };

signals:

	void online_status(bool online);
	void paper_status(bool no_paper);

public slots:

	void start_work();
	void stop_work();

	void print_transaction(TransInfo trans_info);
	void print_transactions(QList<TransInfo> trans_list);
	void print_clr_transaction(ClearInfo clr_info);

private slots:

	void receive_data();
	void check_online();
	void transfer_data(QByteArray data);

private:

    QByteArray rcsv_analyze(QByteArray &raw_data);
	void parse_msg(QByteArray msg);

	void reset();
	void inquiry();
	void set_encoding(uint32_t encoding);
	void set_alignment(uint32_t alignment);
	void set_bold(bool bold);
	void set_double_width(bool double_width);

	void prt_logo();
	void prt_qrcode(TransInfo trans_info);

private:

	QMutex m_mutex;

	SerialConfig m_param;
	QSerialPort *m_port;
	QTimer *m_read_timer;
	QTimer *m_check_timer;
	QTextCodec *m_gb_codec;				// display controller received only GB18030
										// use it to convert from/to UTF8

	QImage *m_logo;

	bool m_online;

	QByteArray m_data;
};

class PrtController : public QObject
{
	Q_OBJECT

public:

    PrtController(QObject *parent = nullptr);
    ~PrtController();

    PrtController_Worker *getWorker() {
        return m_worker;
    }

signals:

	void start();
	void stop();

private:

	QThread m_worker_thread;
	PrtController_Worker *m_worker;

    Coordinator *m_coordinator;
};

#endif
